package com.zjzywl.smoke.controller;

import java.io.File;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.zjzywl.smoke.config.AppConfig;
import com.zjzywl.smoke.entity.HighBuilding;
import com.zjzywl.smoke.util.WebResult;

@RestController
@RequestMapping(value = "/hightBuilding")
public class HighBuildingController extends BaseController {
    @Autowired
    private AppConfig appConfig;

    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /*
     * 添加，修改高层建筑
     */
    @PostMapping(value = "/save")
    public WebResult save( HighBuilding highBuilding, @RequestParam("orgId") Integer orgId, MultipartFile file) {
        try {
            if(!StringUtils.isBlank(file.getOriginalFilename())) {
                
                highBuilding = executeUpload(highBuilding, file);
            }
            ResponseEntity<HighBuilding> history = appConfig.restTemplate().postForEntity(
                    appConfig.getGetDataIp() + "/hightBuilding/save?orgId=" + orgId, highBuilding, HighBuilding.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            // 打印出错
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }

    }

    // 删除建筑
    @DeleteMapping(value = "/delete/{id}")
    public WebResult delete(@PathVariable("id") Integer id) {
        try {
            appConfig.restTemplate().delete(appConfig.getGetDataIp() + "/hightBuilding/delete/" + id);
            return WebResult.OK();
        } catch (Exception e) {
            // 打印出错
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }

    }

    // 根据楼房地址名称模糊查询设备
    @RequestMapping(value = "/getList/likeBuildingName", method = RequestMethod.GET)
    @ResponseBody
    public WebResult getByUserAndDeviceTypeAndAddressLike(HttpServletRequest request) {
        try {
            String userId = this.getUserId();
            ResponseEntity<Object> history = appConfig.restTemplate()
                    .getForEntity(appConfig.getGetDataIp() + "/hightBuilding/getList?userId=" + userId + "&"
                            + URLDecoder.decode(request.getQueryString(), "utf-8"), Object.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            // 打印出错
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }

    }

    /*
     * 图片上传方法
     * 
     */
    private HighBuilding executeUpload(HighBuilding org, MultipartFile file) throws Exception {
        String uploadDir = getUploadDir() + "hightBuilding" + "/";
        // 如果文件不存在，自动创建文件夹
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                logger.error("创建上传目录失败");
            }
        }
        if (file != null) {
            // 文件后缀名
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            // 上传文件名
            String filename = UUID.randomUUID() + suffix;
            // 服务器端保存的文件对象
            File serverFile = new File(uploadDir + filename);
            // 将上传到的文件写入到服务器
            file.transferTo(serverFile);
            org.setPhotoUrl("/upload/" + "hightBuilding" + "/" + filename);
        }
        return org;
    }
}
